package com.island.gomall.service.impl;

import com.island.gomall.dao.CategoryDao;
import com.island.gomall.entity.CategoryEntity;
import com.island.gomall.service.CategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryDao categoryDao;

    @Override
    public List<CategoryEntity> getCategoryWithTree() {
        List<CategoryEntity> entities = categoryDao.selectList();
        List<CategoryEntity> collect = entities.stream()
                .filter(item->item.getParentCid()==0)
                .map(menu->{
                    menu.setChildren(getChildrens(menu,entities));
                    return menu;
                })
                .sorted((menu1,menu2)->{
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return collect;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> entities) {
        List<CategoryEntity> collect = entities.stream()
                .filter(item -> item.getParentCid() == categoryEntity.getCatId())
                .map(menu -> {
                    menu.setChildren(getChildrens(menu, entities));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public boolean removeCategoryNode(int cid) {
        int childrenNum = categoryDao.isExistChildern(cid);
        if(childrenNum == 0){
            categoryDao.logicDelete(cid);
            return true;
        }else{
            return false;
        }

    }

    @Override
    public void addCategoryNode(int parentId, String name) {
        categoryDao.insertCategoryNode(parentId, name);
    }
}
